package com.dearcocoa.utils;

import cn.hutool.json.JSONObject;
import cn.hutool.json.JSONUtil;
import com.dearcocoa.common.BaseException;
import com.dearcocoa.common.BaseResult;
import com.dearcocoa.common.Status;
import lombok.extern.slf4j.Slf4j;

import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * <p>
 *  response通用工具类
 * </p>
 *
 * @Package: com.dearcocoa.utils
 * @ClassName: ResponseUtil
 * @Author: shengong
 * @Date: Created in 2020-07-30 22:28
 * @Version: V1.0
 * @Description: TODO
 */
@Slf4j
public class ResponseUtil {
    /**
     * 往 response 写出 json
     * @param response 响应
     * @param status 状态
     * @param object 数据
     */
    public static void renderJson(HttpServletResponse response, Status status, Object object) {
        try {
            response.setHeader("Access-Control-Allow-Origin", "*");
            response.setHeader("Access-Control-Allow-Methods", "*");
            response.setContentType("application/json;charset=UTF-8");
            response.setStatus(200);
            response.getWriter().
                    write(JSONUtil.toJsonStr(new JSONObject(BaseResult.ofStatus(status, object), false)));
        }catch (IOException e){
            log.error("Response写出JSON异常",e);
        }
    }

    /**
     * 往 response 写出 json
     * @param response 响应
     * @param exception 异常
     */
    public static void renderJson(HttpServletResponse response, BaseException exception) {
        try {
            response.setHeader("Access-Control-Allow-Origin", "*");
            response.setHeader("Access-Control-Allow-Methods", "*");
            response.setContentType("application/json;charset=UTF-8");
            response.setStatus(200);
            response.getWriter().
                    write(JSONUtil.toJsonStr(new JSONObject(BaseResult.ofException(exception), false)));
        }catch (IOException e){
            log.error("Response写出JSON异常",e);
        }
    }
}
